import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'

export class XiuXianSkills extends plugin {
    constructor() {
        super({
            name: '修仙文游技能',
            dsc: '修仙游戏的技能相关功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^学习技能(.*)$', fnc: 'learnSkill' },
                { reg: '^查看技能$', fnc: 'showSkills' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
    }

    async learnSkill(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const skillName = e.msg.replace(/^学习技能/, '').trim()
        const skill = this.data.skills.find(s => s.name === skillName)

        if (!skill) return this.reply('没有找到该技能')
        if (player.lingshi < skill.cost) return this.reply(`灵石不足,学习该技能需要${skill.cost}灵石`)
        if (player.learnedSkills && player.learnedSkills.includes(skill.id)) return this.reply('你已经学会了这个技能')

        player.lingshi -= skill.cost
        if (!player.learnedSkills) player.learnedSkills = []
        player.learnedSkills.push(skill.id)

        Object.entries(skill.effect).forEach(([attr, value]) => {
            player[attr] += value
        })

        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
        this.utils.updateTaskProgress(player, '学习技能')

        return this.reply(`成功学习技能"${skill.name}",消耗${skill.cost}灵石`)
    }

    async showSkills(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const learnedSkills = player.learnedSkills || []
        const skillList = this.data.skills.map(skill => {
            const learned = learnedSkills.includes(skill.id) ? '(已学习)' : ''
            return `${skill.name}${learned}: 花费${skill.cost}灵石
    效果: ${Object.entries(skill.effect).map(([attr, value]) => `${attr}+${value}`).join(', ')}`
        }).join('\n\n')

        const skillText = `
    已学习技能:
    ${learnedSkills.map(id => this.data.skills.find(s => s.id === id).name).join(', ') || '暂无'}
    
    可学习技能:
    ${skillList}
    
    使用"学习技能+技能名"来学习新技能
        `.trim()

        const forwardMsg = await this.utils.markdown(e, skillText, '修仙技能')
        return this.reply(forwardMsg)
    }
}
